from conan import ConanFile
from conan.tools.cmake import cmake_layout
from conan.tools.files import (
    apply_conandata_patches, collect_libs, copy, export_conandata_patches, load,
    get, rename, replace_in_file, rmdir, save, chdir
)
from conan.tools.scm import Version
from conan.tools.gnu import Autotools, AutotoolsToolchain
from conan.tools.env import Environment, VirtualBuildEnv
import os
import re
import textwrap

required_conan_version = ">=1.53.0"


class FreetypeConan(ConanFile):
    name = "freetype"
    description = "FreeType is a freely available software library to render fonts."
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://www.freetype.org"
    license = "FTL"
    topics = ("freetype", "fonts")
    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "with_png": [True, False],
        "with_zlib": [True, False],
        "with_bzip2": [True, False],
        "with_brotli": [True, False],
        "subpixel": [True, False],
    }
    default_options = {
        "shared": False,
        "fPIC": True,
        "with_png": False,
        "with_zlib": False,
        "with_bzip2": False,
        "subpixel": False,
    }

    @property
    def _settings_build(self):
        return getattr(self, "settings_build", self.settings)

    @property
    def _has_with_brotli_option(self):
        return Version(self.version) >= "2.10.2"

    def export_sources(self):
        export_conandata_patches(self)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC
        if not self._has_with_brotli_option:
            del self.options.with_brotli

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")
        self.settings.rm_safe("compiler.cppstd")
        self.settings.rm_safe("compiler.libcxx")

    def layout(self):
        cmake_layout(self, src_folder="src")

    def build_requirements(self):
        if self._settings_build.os == "Windows":
            self.tool_requires("libtool/2.4.7")
            self.win_bash = True
            if not self.conf.get("tools.microsoft.bash:path", check_type=str):
                self.tool_requires("msys2/cci.latest")

    def requirements(self):
        if self.options.with_png:
            self.requires("libpng/1.6.40")
        if self.options.with_zlib:
            self.requires("zlib/[>=1.2.10 <2]")
        if self.options.with_bzip2:
            self.requires("bzip2/1.0.8")
        # if self.options.get_safe("with_brotli"):
        #     self.requires("brotli/1.1.0")

    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)

    def generate(self):
        env = VirtualBuildEnv(self)
        env.generate()
        tc = AutotoolsToolchain(self)
        if not self.options.shared:
            tc.extra_cflags.append("-fPIC")
            tc.extra_cxxflags.append("-fPIC")
        tc.generate()
        

    def build(self):
        withLibs = []

        lib_type = "--enable-static --disable-shared"
        if self.options.shared:
            lib_type = "--enable-shared --disable-static"

        if not self.options.with_zlib:
            withLibs.append("--without-zlib")
        if not self.options.with_png:
            withLibs.append("--without-png")
        if not self.options.with_bzip2:
            withLibs.append("--without-bzip2")


        with chdir(self, self.source_folder):
            self.run("./autogen.sh --host={} --target={} {}".format("arm64-linux-ohos", "arm64-linux-ohos", lib_type))
            autotools = Autotools(self)
            autotools.configure(args=withLibs)
            autotools.make()

    def package(self):
        if self.options.shared:
            copy(self, "*.so*", src=os.path.join(self.source_folder, "objs", ".libs"), dst=os.path.join(self.package_folder, "libs"))
        else :
            copy(self, "*.a", src=os.path.join(self.source_folder, "objs", ".libs"), dst=os.path.join(self.package_folder, "libs"))
        copy(self, "*.h", src=os.path.join(self.source_folder, "include"), dst=os.path.join(self.package_folder, "include"))

        pass


    @staticmethod
    def _chmod_plus_x(filename):
        if os.name == "posix" and (os.stat(filename).st_mode & 0o111) != 0o111:
            os.chmod(filename, os.stat(filename).st_mode | 0o111)

    def package_info(self):
        self.cpp_info.set_property("cmake_find_mode", "both")
        self.cpp_info.set_property("cmake_module_file_name", "Freetype")
        self.cpp_info.set_property("cmake_file_name", "freetype")
        self.cpp_info.set_property("cmake_target_name", "Freetype::Freetype")
        self.cpp_info.set_property("cmake_target_aliases", ["freetype"]) # other possible target name in upstream config file
        # self.cpp_info.set_property("cmake_build_modules", [self._module_vars_rel_path])
        self.cpp_info.set_property("pkg_config_name", "freetype2")
        self.cpp_info.libs = collect_libs(self)
        if self.settings.os in ["Linux", "FreeBSD"]:
            self.cpp_info.system_libs.append("m")
        self.cpp_info.includedirs.append(os.path.join("include", "freetype2"))

        # libtool_version = load(self, self._libtool_version_txt).strip()
        # self.conf_info.define("user.freetype:libtool_version", libtool_version)
        # FIXME: need to do override the pkg_config version (pkg_config_custom_content does not work)
        # self.cpp_info.version["pkg_config"] = pkg_config_version

        # TODO: to remove in conan v2 once cmake_find_package* & pkg_config generators removed
        self.cpp_info.filenames["cmake_find_package"] = "Freetype"
        self.cpp_info.filenames["cmake_find_package_multi"] = "freetype"
        self.cpp_info.names["cmake_find_package"] = "Freetype"
        self.cpp_info.names["cmake_find_package_multi"] = "Freetype"
        # self.cpp_info.build_modules["cmake_find_package"] = [self._module_vars_rel_path]
        # self.cpp_info.build_modules["cmake_find_package_multi"] = [self._module_target_rel_path]
        self.cpp_info.names["pkg_config"] = "freetype2"
        freetype_config = os.path.join(self.package_folder, "bin", "freetype-config")
        self.env_info.PATH.append(os.path.join(self.package_folder, "bin"))
        self.env_info.FT2_CONFIG = freetype_config
        self._chmod_plus_x(freetype_config)
        # self.user_info.LIBTOOL_VERSION = libtool_version
